package elementaryAlgorithm;

/**
 * @author 郭辉
 * @className TODO
 * @description 61. 旋转链表
 * 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
 *
 *
 *
 * 示例 1：
 *
 *
 * 输入：head = [1,2,3,4,5], k = 2
 * 输出：[4,5,1,2,3]
 * 示例 2：
 *
 *
 * 输入：head = [0,1,2], k = 4
 * 输出：[2,0,1]
 *
 *
 * 提示：
 *
 * 链表中节点的数目在范围 [0, 500] 内
 * -100 <= Node.val <= 100
 * 0 <= k <= 2 * 109
 * 通过次数310,625提交次数748,737
 * @date 2023/4/25 11:19
 * @company 海康威视
 * @since 1.0.0
 */
public class Leet61 {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null || k ==0){
            return head;
        }
        int length = 1;
        //左右指针初始化
        ListNode left= head,right = null;
        while (left.next != null){
            left = left.next;
            length ++ ;
        }
        k = k %length;
        right = left;
        left = head;
        //循环链表
        right.next = left;
        for (int i = 0; i < length-k; i++) {
            left = left.next;
            right = right.next;
        }
        right.next = null;
        return left;
    }

    public static void main(String[] args) {
        Leet61 leet61 = new Leet61();
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        ListNode node = leet61.rotateRight(node1, 2);
        System.out.println(node);
    }
}
